package com.cyss.greenball.world;

import java.util.LinkedHashSet;
import java.util.Set;

import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;

import android.graphics.Canvas;

import com.cyss.greenball.exception.GameOverException;
import com.cyss.greenball.util.SystemUtil;

public class BallWorld {
	private AABB worldAABB;
	private World world;
	private Vec2 gravity;
	private boolean doSleep;
	private Set<ElementObject> elementList;
	private Set<Hole> holeElement;

	public BallWorld() {
		
		elementList = new LinkedHashSet<ElementObject>();
		holeElement = new LinkedHashSet<Hole>();
		float screenWidth = SystemUtil.SCREEN_WIDTH, screenHeight = SystemUtil.SCREEN_HEIGHT;
		gravity = new Vec2(0.0f, 10.0f);
		doSleep = true;
		worldAABB = new AABB();
		worldAABB.lowerBound.set(-1.0f, -1.0f);
		worldAABB.upperBound.set((float) screenWidth / SystemUtil.RATE + 1.0f,
				(float) screenHeight / SystemUtil.RATE + 1.0f);
		world = new World(worldAABB, gravity, doSleep);
	}

	public void setGravity(float x, float y) {
		world.setGravity(new Vec2(x, y));
	}

	public void addElementObject(ElementObject e) {
		this.elementList.add(e);
	}

	public void addHoleElement(Hole hole) {
		this.holeElement.add(hole);
		this.elementList.add(hole);
	}

	public void DrawAllElement(Canvas canvas) throws GameOverException {
		world.step(SystemUtil.TIMESTEP, SystemUtil.ITERATIONS);
		for (ElementObject e : this.elementList) {
			e.onDraw(canvas);
		}
	}

	public Set<Hole> getHoleElement() {
		return holeElement;
	}

	public World getWorld() {
		return world;
	}
}
